import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { allRoutes, route404 } from './router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const token = store.state.user.token
    if (token) {
        if (to.path === '/login') {
            next('/')
            NProgress.done()
        } else {
            if (!store.state.user.userInfo.userId) {
                const res = await store.dispatch('user/getUserInfo')
                const userRoutes = allRoutes.filter(e => {
                    return res.includes(e.children[0].name)
                })
                store.commit('menus/setMenus', userRoutes)
                router.addRoutes(userRoutes)
                next(to)
            } else {
                next()
            }
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
})

router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    next()
})

router.afterEach(() => {
    NProgress.done()
})
